import jwt
from fastapi import APIRouter, Depends, Body
from sqlalchemy.orm import Session
from starlette.requests import Request

from FastApi import ErrorCode
from FastApi.Common import Success, Result, Error
from FastApi.Database import GetDb
from FastApi.Model.UserModel import UserModel
from Lib.Utils import Password

user_router = APIRouter()


@user_router.post("/login")
async def login(user_name: str = Body(str, embed=True),
                user_pass: str = Body(str, embed=True),
                db: Session = Depends(GetDb)):
    user_model = UserModel()
    res_user = user_model.LoginByUserNameAndPwd(db, user_name, user_pass)
    return Result(res_user, "登陆成功", ErrorCode.USER_OR_PASS_ERROR, "用户名或密码错误")


@user_router.get("/index")
async def index():
    return {}


@user_router.post("/regist")
async def register(user_name: str = Body(str, embed=True),
                   user_pass: str = Body(str, embed=True),
                   db: Session = Depends(GetDb)):
    user_model = UserModel()
    res_user = user_model.Add(db, user_name, Password(user_pass))
    return Success(res_user, "获取成功") if res_user else user_model.GetError()


@user_router.get('/oauth/{token}')
async def oauth(token: str, request: Request, db: Session = Depends(GetDb)):
    # 设备 和 token 验证
    # header = request.headers
    # header_device = header['X-Device']
    # if not header_device == "app": return Error(ErrorCode.DEVICE_MATCH_ERROR, "设备不正确，请选用app登陆")
    # header_token = header['X-token']

    # 根据token获取用户信息
    # res_user_info = UserTokenModel().GetUserInfo(header_token, header_device, db)
    # print(res_user_info)

    data = jwt.decode(token, "JWT_KEY", algorithms=['HS256'])
    address = data['address']
    return {"host": address[0], "port": address[1]}
    # return templates.TemplateResponse("oauth.html", {"request": request, "host": address[0], "port": address[1]})

user_controller = user_router